<script setup>

import CardBox from "@/components/CardBox/index.vue";
import {useRouter} from "vue-router";
import {Download} from "@element-plus/icons-vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {
  addAchievementApi,
  addCertificateApi, deleteActualOutPutApi, deleteCertificateApi,
  detailsAcademicOutputApi,
  detailsCertificateApi,
  downWallAcademicOutputApi,
  getAchievementListApi,
  getAllCertificateTypeApi,
  getCertificateListApi,
  getStudentListApi, unWallCertificateApi,
  updateAcademicOutputApi,
  updateCertificateApi,
  wallAcademicOutputApi,
  wallCertificateApi
} from "@/api/school.js";
import useUserStore from "@/store/modules/user.js";
import {checkRole} from "@/utils/permission.js";
import FileUpload from "@/components/FileUpload/index.vue";
import {formatDateNoTime} from "@/utils/index.js";

const router = useRouter()
const {proxy} = getCurrentInstance();
const user = useUserStore()

const state = reactive({
  permission:[],
  studentList: [],
  formRules: {
    stuId: [
      {required: true, message: '请选择学生', trigger: 'change'},
    ],
    acTitle: [
      {required: true, message: '请输入证书标题', trigger: 'blur'},
    ],
    certTypeId: [
      {required: true, message: '请选择证书类型', trigger: 'change'},
    ],
    acScore: [
      {required: true, message: '请输入考试得分', trigger: 'blur'},
    ],
    acPass: [
      {required: true, message: '请选择是否通过', trigger: 'change'},
    ],
    acFile: [
      {required: true, message: '请上传证书材料', trigger: 'change'},
    ],
    acLevel: [
      {required: true, message: '是否等级考试', trigger: 'change'},
    ],
    acDanwei: [
      {required: true, message: '请输入证书批准单位', trigger: 'blur'},
    ],
    acTime: [
      {required: true, message: '请选择时间', trigger: 'change'},
    ],
  },
  editForm: {
    id: '',
    stuId: '',
    acTitle: '',
    acFile: '',
    acScore: '',
    acPass: '',
    acLevel: '',
    acTime:'',
  },
  achievementTypeList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stuName: '',
    stuNum: '',
    stuFaculties: '',
    stuPhone: '',
    yearEnrollment: '',
    stuClass: '',
    acTitle: '',
    acWall: '',
  },
  total: 0,
  title: '新增技能证书',
  ids: [],
  certTypeList: [],
})

const showDia1 = ref(false)
const selectable = (row) => ![].includes(row.id)
const handleAdd = async () => {
  const res = await getStudentListApi()
  if (res.code == 200) {
    state.studentList = res.data
  }
  showDia1.value = true
}

const handleUploadSuccess = (response, file, fileList) => {
  console.log(response, file, fileList)
}

const handleEdit = async (id) => {

  // 获取详情
  const res = await detailsCertificateApi({id})

  if (res.code == 200) {
    // 查看当前选择的有没有这个人
    const res1 = await getStudentListApi()
    if (res.code == 200) {
      state.studentList = res1.data
      const index = state.studentList.findIndex(item => item.id == res.data.stuId)
      if (index === -1) {
        state.studentList.push({
          id: res.data.stuId,
          stuName: res.data.stuName,
        })
      }
    }


    state.editForm = res.data
    showDia1.value = true
    state.title = '编辑证书'
  }
}

const getDataList = async () => {
  state.queryParams.acTime = formatDateNoTime(state.queryParams.acTime)
  const res = await getCertificateListApi(state.queryParams)
  if (res.code == 200) {
    state.tableData = res.rows
    state.total = res.total
  }
}

const resetSearch = () => {
  proxy.resetForm("queryRef");
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
  }
  getDataList()
}

// 跳转审核
const jumpAudit = () => {
  // 判断角色-老师和队长
  if (checkRole(['teacher'])) {
    router.push('/approvalManagement/teacherApproval')
  } else if (checkRole(['captain'])) {
    router.push('/approvalManagement/captainApproval')
  }
}

const getAllCertTypeList = async () => {
  const res = await getAllCertificateTypeApi()
  if (res.code == 200) {
    state.certTypeList = res.data
  }
}

const submitForm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      let res = ''
      if (state.editForm.id == '') {
        res = await addCertificateApi(state.editForm)
      } else {
        res = await updateCertificateApi(state.editForm)
      }

      if (res.code == 200) {
        proxy.$message.success('操作成功')
        handleClose()
        await getDataList()
      }
    }
  })
}

const handleClose = () => {
  showDia1.value = false
  state.editForm = {
    id: '',
    acTitle: '',
    acFile: '',
    acScore: '',
    acPass: '',
    acLevel: '',
  }
  proxy.resetForm("formRef");
  state.title = '新增技能证书'
}

// 改变类型选择
const changeType = (e) => {
  const one = state.certTypeList.find(item => item.id === e)
  state.editForm.acLevel = one.certLevel
}

const searchStudent = async (query) => {
  const res = await getStudentListApi({stuName: query})
  if (res.code == 200) {
    state.studentList = res.data
  }
}

const handleWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否上墙该数据？').then(async () => {
      const res = await wallCertificateApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleDownWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否下墙该数据？').then(async () => {
      const res = await unWallCertificateApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleChecked = (id, checked) => {
  const index = state.ids.findIndex(item => item.id === id)
  if (index !== -1) {
    state.ids.splice(index, 1)
  } else {
    state.ids.push(id)
  }
}

const handleDelete = (id) => {
  proxy.$modal.confirm('是否删除该数据？').then(async () => {
    const res = await deleteCertificateApi({id})
    if (res.code == 200) {
      proxy.$modal.msgSuccess("删除成功")
    }
    await getDataList()
  })
}

const handleExport = async (item) => {
  proxy.download("/school/pacProSkillCert/export-word", {
    id: item.id
  },`${item.stuName}证书情况.docx`);
}
const userStore = useUserStore()

// 获取当前老师的权限信息
const getPermission = async () => {
  state.permission = userStore.roles
  if(state.permission.includes('teacher')){
    state.queryParams.teacherType = 0
  }else{
    state.queryParams.teacherType = 1
  }
}

const handleExport2 = () => {
  proxy.download("/school/pacProSkillCert/export-word2", {
    ids: state.ids
  },`证书批量导出${new Date().getTime()}.docx`);
}

const handleSelectionChange = (val) => {
  state.ids = val.map(item => item.id)
}

onMounted(() => {
  getPermission()
  getDataList()
  getAllCertTypeList()
})
</script>

<template>
  <div class="outBox">
    <CardBox style="margin-bottom: 20px" title="筛选查询">
      <template #btn-cont>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </template>
      <template #content>
        <el-form :model="state.queryParams" ref="queryRef" label-width="auto" inline="true">
          <el-form-item label="姓名">
            <el-input v-model="state.queryParams.stuName"/>
          </el-form-item>
          <el-form-item label="学号">
            <el-input v-model="state.queryParams.stuNum"/>
          </el-form-item>
          <el-form-item label="班级">
            <el-input v-model="state.queryParams.stuClass"/>
          </el-form-item>
          <el-form-item label="证书批准时间">
            <el-date-picker
                v-model="state.queryParams.acTime"
                type="date"
                placeholder="请选择"
            />
          </el-form-item>
          <el-form-item label="证书批准单位">
            <el-input v-model="state.queryParams.acDanwei"/>
          </el-form-item>
          <el-form-item label="证书名称">
            <el-input v-model="state.queryParams.acTitle"/>
          </el-form-item>
          <el-form-item label="是否上墙">
            <el-select v-model="state.queryParams.acWall" style="width: 170px;" placeholder="请选择">
              <el-option label="是" value="2"/>
              <el-option label="否" value="1"/>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </CardBox>
    <CardBox title="数据列表">
      <template #btn-cont>
<!--        <el-button type="primary" @click="handleWall">上墙</el-button>-->
<!--        <el-button type="primary" @click="handleDownWall">下墙</el-button>-->
<!--        <el-button type="primary" @click="jumpAudit">证书审核</el-button>-->
<!--        <el-button type="primary" @click="handleAdd">上传证书</el-button>-->
        <el-select v-model="state.queryParams.teacherType" placeholder="请选择" @change="getDataList"
                   v-if="!state.permission.includes('superManager') && !state.permission.includes('admin')"
                   style="width: 150px;margin-right: 15px">
          <el-option label="学业导师" :value="0" v-if="state.permission.includes('teacher')"/>
          <el-option label="专业教师" :value="1" v-if="state.permission.includes('teacher2')"/>
          <el-option label="中队长" :value="3" v-if="state.permission.includes('duizhang')"/>
        </el-select>
        <el-button type="primary" @click="handleExport2">导出</el-button>
      </template>
      <template #content>
        <el-table :data="state.tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="selectable" width="55">
<!--            <template #default="scope">-->
<!--              <el-checkbox v-model="scope.row.checked" @change="handleChecked(scope.row.id, scope.row.checked)"/>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column prop="a" label="姓名" align="center">
            <template #default="scope">
              {{ scope.row.student.stuName }}
            </template>
          </el-table-column>
          <el-table-column prop="b" label="学号" align="center">
            <template #default="scope">
              {{ scope.row.student.stuNum }}
            </template>
          </el-table-column>
          <el-table-column prop="e" label="班级" align="center">
            <template #default="scope">
              {{ scope.row.student.stuClass }}
            </template>
          </el-table-column>
          <el-table-column prop="acTime" label="证书批准时间" align="center">
            <template #default="scope">
              {{ formatDateNoTime(scope.row.acTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="acDanwei" label="证书批准单位" align="center"/>
          <el-table-column prop="isGraduated" label="是否毕业要求证书" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.isGraduated === 0" type="info">否</el-tag>
              <el-tag v-if="scope.row.isGraduated === 1" type="success">是</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="acTitle" label="证书名称" align="center"/>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="handleEdit(scope.row.id)">证书详情</el-button>
              <el-button type="primary" size="small" link @click="handleExport(scope.row)">导出</el-button>
              <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)" v-if="state.queryParams.teacherType !== 3">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pageBox">
          <pagination
              v-show="state.total > 0"
              :total="state.total"
              v-model:page="state.queryParams.pageNum"
              v-model:limit="state.queryParams.pageSize"
              @pagination="getDataList()"
          />
        </div>
      </template>
    </CardBox>

    <el-dialog :title="state.title" v-model="showDia1" width="800" >
      <div>
        <el-form label-width="150px" ref="formRef" :rules="state.formRules" :model="state.editForm">
          <el-row>
            <el-col :span="24">
              <el-form-item label="学生" prop="stuId">
                <el-select v-model="state.editForm.stuId"
                           placeholder="请选择"
                           style="width: 200px;"
                           filterable
                           remote
                           reserve-keyword
                           :remote-method="searchStudent">
                  <el-option v-for="item in state.studentList" :key="item.id"
                             :label="`${item.stuClass}-${item.stuName}`" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="证书批准时间" prop="acTime">
                <el-date-picker
                    v-model="state.editForm.acTime"
                    type="date"
                    placeholder="选择日期"
                    style="width: 200px;"
                    value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="证书批准单位" prop="acDanwei">
                <el-input v-model="state.editForm.acDanwei" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="证书名称" prop="acTitle">
                <el-input v-model="state.editForm.acTitle" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="证书类型" prop="certTypeId">
                <el-select v-model="state.editForm.certTypeId" placeholder="请选择" @change="changeType">
                  <el-option
                      v-for="item in state.certTypeList"
                      :key="item.id"
                      :label="item.certName"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否等级考试" prop="acLevel">
                <el-radio-group v-model="state.editForm.acLevel" disabled>
                  <el-radio label="是" :value="1"></el-radio>
                  <el-radio label="否" :value="0"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="state.editForm.acLevel == 1">
              <el-form-item label="等级考试得分" prop="acScore">
                <el-input v-model="state.editForm.acScore"/>
              </el-form-item>
            </el-col>
<!--            <el-col :span="24" v-if="state.editForm.acLevel == 1">-->
<!--              <el-form-item label="是否通过等级考试" prop="acPass">-->
<!--                <el-radio-group v-model="state.editForm.acPass">-->
<!--                  <el-radio label="通过" :value="1"></el-radio>-->
<!--                  <el-radio label="未通过" :value="0"></el-radio>-->
<!--                </el-radio-group>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label="上传证书材料：" label-position="top" label-width="150" prop="acFile">
                <div class="uploadBox">
                  <FileUpload
                      :multiple="false"
                      :limit="1"
                      v-model="state.editForm.acFile"
                      :fileType="['png', 'jpg','jpeg','pdf']"
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form label-width="150" label-position="top">

        </el-form>

        <div class="footer">
          <el-button @click="handleClose">返回</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.uploadBox {
  margin-left: 50px;
}

.footer {
  text-align: center;
}

.tags {
  position: relative;
  width: 150px;
  height: 40px;

  :deep(.el-tag) {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
  }
}
</style>
